package com.sunshuo.springsecuritydemo.controller;

import com.sunshuo.springsecuritydemo.pojo.Role;
import com.sunshuo.springsecuritydemo.pojo.UserRole;
import com.sunshuo.springsecuritydemo.service.RoleService;
import com.sunshuo.springsecuritydemo.service.UserRoleService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserRoleController
 * @Description
 * @Author sunshuo
 * @Date 2021/11/7 20:56
 */
@Controller
@RequestMapping("/user_role")
public class UserRoleController {

    private UserRoleService userRoleService;

    private RoleService roleService;

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @Autowired
    public void setUserRoleService(UserRoleService userRoleService) {
        this.userRoleService = userRoleService;
    }

    @RequestMapping("/query_user_role_tree")
    @ResponseBody
    public String queryUserRoleTree(String userId) {
        List<UserRole> relations = userRoleService.getRoleRelationsByUserId(userId);
        List<String> rolesId = new ArrayList<>();
        relations.forEach(relation -> {
            rolesId.add(relation.getRoleId());
        });

        List<Role> roles = roleService.getRoles();

        JSONArray results = new JSONArray();
        roles.forEach(role -> {
            JSONObject data = new JSONObject();
            data.put("id", role.getId());
            data.put("title", role.getName());
            data.put("checked", rolesId.contains(role.getId()));
            results.put(data);
        });

        return results.toString();
    }

    @RequestMapping("/update_relation")
    @ResponseBody
    public String updateRelation(String userId, String roleInfo) {
        JSONObject results = new JSONObject();
        try {
            List<UserRole> userRoles = new ArrayList<>();
            JSONArray  roleInfos = new JSONArray(roleInfo);
            for (int i = 0; i < roleInfos.length(); i++) {
                JSONObject jsonObject = roleInfos.getJSONObject(i);
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(jsonObject.getString("id"));
                userRoles.add(userRole);
            }
            userRoleService.updateUserRole(userId, userRoles);
            results.put("code", 200);
            return results.toString();
        } catch (Exception e) {
            results.put("code", 500);
            results.put("message", "更新失败");
        }
        return results.toString();
    }

}
